<template>
  <el-button type="success" text @click="addPhone">
    <el-icon>
      <Plus />
    </el-icon>
    添加手机
  </el-button>
  <div class="">
    <el-table :data="filterTableData" style="width: 100%">
      <el-table-column label="注册日期" prop="createTime" />
      <el-table-column label="封面">
        <template #default="scope">
          <img :src="scope.row.coverSrc" />
        </template>
      </el-table-column>
      <el-table-column label="品牌" prop="brandName" />
      <el-table-column label="类型" prop="typeName" />
      <el-table-column label="名字" prop="phoneName" />
      <el-table-column label="内存" prop="memory" />
      <el-table-column label="硬盘" prop="disk" />
      <el-table-column label="颜色" prop="color" />
      <el-table-column label="价格" prop="price" />
      <el-table-column label="状态">
        <template #default="scope">

          <el-tag :type="scope.row.isDelete == 0 ? 'error' : 'success'" disable-transitions>{{ scope.row.isDelete == 0 ?
            '已下架' : '未下架' }}</el-tag>


        </template>
      </el-table-column>
      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="搜索" />
        </template>
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">查看评论</el-button>
          <el-button type="success" @click="upOrDown(scope.row)">{{ scope.row.isDelete == 0 ? '上架' : '下架' }}</el-button>
          <el-button type="error" @click="changePhone(scope.row)">修改</el-button>

        </template>
      </el-table-column>
    </el-table>
  </div>
  <div>
    <div class="footer">
      <el-pagination @current-change="currentChange" :total="totalValue" :default-current-page="1"
        v-model:current-page="currentPage" :page-size="pageSize" layout="prev, pager, next" />
    </div>
  </div>

  <el-dialog v-model="commentDialog" title="Tips" width="700px">

    <el-table :data="commnents" style="width: 100%">
      <el-table-column label="评论人" prop="userName" />

      <el-table-column label="评论信息" prop="msg" />
      <el-table-column label="评论信息">
        <template #default="scope">


          <el-tag :type="scope.row.status == 0 ? 'error' : 'success'" disable-transitions> {{ scope.row.status == 0 ?
            '未通过' : '已通过' }}</el-tag>

        </template>
      </el-table-column>
      <el-table-column label="评分">
        <template #default="scope">

          <el-rate v-model="scope.row.rate" disabled show-score text-color="#ff9900" score-template="{value} points" />

        </template>
      </el-table-column>




      <el-table-column align="right">
        <template #header>
          <el-input v-model="search" size="small" placeholder="搜索" />
        </template>
        <template #default="scope">
          <el-button v-if="scope.row.status == 0" size="small" @click="pass(scope.row)">
            通过</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>





  <el-dialog v-model="dialogVisible" title="Tips" width="30%">
    <div class="container">
      <div>
        <el-steps :space="200" :active="step" finish-status="success">
          <el-step title="选择品牌" />
          <el-step title="选择系列" />
          <el-step title="具体描述" />
        </el-steps>
      </div>

      <div class="selecter">

        <div v-show="step == 0" class="select-item">
          <div>
            <el-select v-model="phoneInfo.brandId" class="m-2" placeholder="Select" size="large">
              <el-option v-for="item in brands" :key="item.id" :label="item.msg" :value="item.id" />
            </el-select>
          </div>

          <div>
            <el-button @click="addBrand = true">添加新品牌</el-button>
            <div v-if="addBrand">
              品牌名：<el-input v-model="msg"></el-input>
              <el-button @click="doAdd">添加</el-button>
            </div>

          </div>
        </div>
        <div v-show="step == 1" class="select-item">
          <div>
            <el-select v-model="phoneInfo.typeId" class="m-2" placeholder="Select" size="large">
              <el-option v-for="item in types" :key="item.id" :label="item.msg" :value="item.id" />
            </el-select>
          </div>
          <el-button @click="addType = true">添加新系列</el-button>
          <div v-if="addType">
            类型名：<el-input v-model="msg"></el-input>
            <el-button @click="doAdd">添加</el-button>
          </div>

        </div>
        <div v-show="step == 2">
          <el-form :label-position="labelPosition" label-width="100px" :model="phoneInfo" style="max-width: 460px">
            <el-form-item label="封面">
              <el-upload class="avatar-uploader" action="http://localhost:8848/phone/IMGupload" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="phoneInfo.coverSrc" :src="phoneInfo.coverSrc" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
            <el-form-item label="手机名">
              <el-input v-model="phoneInfo.phoneName" />
            </el-form-item>
            <el-form-item label="内存容量">
              <el-input v-model="phoneInfo.memory" />
            </el-form-item>
            <el-form-item label="硬盘容量">
              <el-input v-model="phoneInfo.disk" />
            </el-form-item>
            <el-form-item label="价格">
              <el-input v-model="phoneInfo.price" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="phoneInfo.des" />
            </el-form-item>
            <el-form-item>
              <div class="mb-2 flex items-center text-sm">
                <el-radio-group v-model="phoneInfo.colorId" class="ml-4">
                  <el-radio v-for="item in colors " :label="item.id" size="large">{{ item.color }}</el-radio>
                </el-radio-group>
              </div>
            </el-form-item>
          </el-form>
        </div>

      </div>

      <div class="buttons">
        <el-button @click="step--">上一步</el-button>
        <el-button @click="next">{{ step < 2 ? '下一步' : '提交' }}</el-button>
      </div>

    </div>

  </el-dialog>


  <!-- <el-button text @click="dialogVisible = true">
    click to open the Dialog
  </el-button> -->

  <el-dialog v-model="changeDialog" title="Tips" width="30%">

    <el-form :label-position="labelPosition" label-width="100px" :model="phoneInfo" style="max-width: 460px">
      <el-form-item label="封面">
        <el-upload class="avatar-uploader" action="http://localhost:8848/phone/IMGupload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="phoneInfo.coverSrc" :src="phoneInfo.coverSrc" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="手机名">
        <el-input v-model="phoneInfo.phoneName" />
      </el-form-item>
      <el-form-item label="内存容量">
        <el-input v-model="phoneInfo.memory" />
      </el-form-item>
      <el-form-item label="硬盘容量">
        <el-input v-model="phoneInfo.disk" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="phoneInfo.price" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="phoneInfo.des" />
      </el-form-item>
      <el-form-item>
        <div class="mb-2 flex items-center text-sm">
          <el-radio-group v-model="phoneInfo.colorId" class="ml-4">
            <el-radio v-for="item in colors " :label="item.id" size="large">{{ item.color }}</el-radio>
          </el-radio-group>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="doChange">
          修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">

import { ElMessage } from 'element-plus';
import { computed, ref, reactive } from 'vue'
import { count, pageList, upOrDownApi } from '../../api/phone'

import { getAllComment, passApi } from '../../api/comment'




import { add, getInfoChildrenByPid } from '../../api/info'
import { getColors } from '../../api/color'
import { savePhone, phoneChangeApi } from '../../api/phone'

import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'


const step = ref(0)

const dialogVisible = ref(false)

const brands = ref()

const types = ref()

const colors = ref()

const labelPosition = ref('right')

const phoneInfo = ref({
  brandId: '',
  typeId: '',
  phoneName: '',
  memory: '',
  disk: '',
  price: 0,
  colorId: '',
  coverSrc: '',
  des: '',
  id: ''
})


const addBrand = ref(false)
const addType = ref(false)
const msg = ref('')

const doAdd = () => {
  console.log(step.value);
  add({
    parentId: step.value == 0 ? 0 : phoneInfo.value.brandId,
    msg: msg.value
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      if (step.value == 0) {
        getInfoChildrenByPid('0').then(res => {
          brands.value = res.data.data
        })
      } else {
        getInfoChildrenByPid(phoneInfo.value.brandId as string).then(res => {
          types.value = res.data.data
        })
      }
      addBrand.value = false
      addType.value = false
    }
  })

}

const changeDialog = ref(false)
const changePhone = (row: any) => {
  changeDialog.value = true
  phoneInfo.value = row
}

const commnents = ref<Array<any>>()


const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  phoneInfo.value.coverSrc = URL.createObjectURL(uploadFile.raw!)
  console.log(response);
  phoneInfo.value.coverSrc = response.data

}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}





const upOrDown = (row: any) => {
  upOrDownApi({
    id: row.id
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      pageList((currentPage.value - 1) * pageSize.value, pageSize.value).then(res => {
        tableData.value = res.data.data
        console.log(tableData.value);

      })
    }
  })
}

const doChange = () => {
  phoneChangeApi(phoneInfo.value).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      pageList((currentPage.value - 1) * pageSize.value, pageSize.value).then(res => {
        tableData.value = res.data.data
        console.log(tableData.value);

      })
      changeDialog.value = false

    }
  })
}

const next = () => {
  step.value++



  if (step.value === 1) {
    // types = PID = brandID
    console.log(phoneInfo.value.brandId);

    getInfoChildrenByPid(phoneInfo.value.brandId as string).then(res => {
      types.value = res.data.data
    })

    getColors().then(res => {
      colors.value = res.data.data
    })

  }

  if (step.value === 3) {
    // commit 
    console.log(phoneInfo);
    savePhone(phoneInfo.value).then(res => {
      dialogVisible.value = false
      step.value = 0;

      count().then(res => {
        totalValue.value = res.data.data
        console.log(totalValue.value + '------------');
      })
      pageList((currentPage.value - 1) * pageSize.value, pageSize.value).then(res => {
        tableData.value = res.data.data
        console.log(tableData.value);

      })

    })

  }
}

const addPhone = () => {
  getInfoChildrenByPid('0').then(res => {
    brands.value = res.data.data
  })
  dialogVisible.value = true
}

const pass = (row: any) => {
  console.log(row);
  passApi({
    id: row.id
  }).then(res => {
    if (res.data.code == 200) {
      ElMessage({
        message: res.data.msg,
        type: 'success'
      })
      getAllComment(row.phoneId).then(res => {
        commnents.value = res.data.data
        console.log(commnents.value);

      })
    }
  })
}








const totalValue = ref()
const pageSize = ref(7)
const currentPage = ref(1)
const commentDialog = ref(false)
const phoneId = ref('')


const search = ref('')


const filterTableData = computed(() =>
  tableData.value.filter(
    (data: any) =>
      !search.value ||
      data.phoneName.toLowerCase().includes(search.value.toLowerCase())
  )
)


const currentChange = (page: number) => {
  pageList((page - 1) * pageSize.value, pageSize.value).then(res => {
    tableData.value = res.data.data
    console.log(tableData.value);

  })
}
count().then(res => {
  totalValue.value = res.data.data
  console.log(totalValue.value + '------------');

})

pageList(0, pageSize.value).then(res => {
  tableData.value = res.data.data
  console.log(tableData.value);

})

const handleEdit = (index: number, row: any) => {
  console.log(index, row)
  commentDialog.value = true

  getAllComment(row.id).then(res => {
    commnents.value = res.data.data
    console.log(commnents.value);

  })
}



const tableData = ref<Array<any>>([])
</script>

<style scoped >
.footer {
  width: 700px;
  margin: 0 auto;
}

img {
  height: 50px
}

.container {
  height: 500px;
}

.body {
  flex: 1;
}

.buttons {
  margin-top: 80px;
}


.avatar-uploader .avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  text-align: center;
}

.select-item {
  display: flex;
  flex-direction: row;
}
</style>